package com.cartrentalsystem.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cartrentalsystem.domain.dto.RentalDto;
import com.cartrentalsystem.domain.po.Car;
import com.cartrentalsystem.domain.po.Customers;
import com.cartrentalsystem.domain.po.Rental;
import com.cartrentalsystem.domain.vo.RentalVo;
import com.cartrentalsystem.domain.vo.Result;
import com.cartrentalsystem.mapper.RentalMapper;
import com.cartrentalsystem.service.ICarService;
import com.cartrentalsystem.service.ICustomersService;
import com.cartrentalsystem.service.IRentalService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LHD
 * @since 2025-06-15
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class RentalServiceImpl extends ServiceImpl<RentalMapper, Rental> implements IRentalService {

    private final ICustomersService customersService;

    private final ICarService carService;

    @Override
    public Result<Page<RentalVo>> list(Integer page, Integer size, String customerName,String plateNumber, Integer status){
        // 姓名处理
        List<Integer> customerIdList=new ArrayList<>();
        if (customerName != null&&!customerName.isEmpty()){
            List<Customers> customerList = customersService.lambdaQuery()
                    .like( Customers::getName, customerName)
                    .eq(Customers::getDeleted, 0)
                    .select(Customers::getId)
                    .list();
            for (Customers customers : customerList) {
                customerIdList.add(customers.getId());
            }
        }

        // 车辆处理
        List<Integer> carIdList=new ArrayList<>();
        if (plateNumber != null&&!plateNumber.isEmpty()){
            List<Car> carList = carService.lambdaQuery()
                    .like(Car::getPlateNumber, plateNumber)
                    .eq(Car::getDeleted, 0)
                    .select(Car::getId)
                    .list();
            for (Car car : carList) {
                carIdList.add(car.getId());
            }
        }


        Page<Rental> list = this.lambdaQuery()
                .eq(Rental::getDeleted, 0)
                .in(!customerIdList.isEmpty(),Rental::getCustomerId, customerIdList)
                .in(!carIdList.isEmpty(),Rental::getCarId, carIdList)
                .eq(status != null, Rental::getStatus, status)
                .page(Page.of(page, size));
        List<RentalVo> rentalVos = new ArrayList<>(list.getRecords().size());
        for (Rental rental : list.getRecords()) {
            Integer carId = rental.getCarId();
            Integer customerId = rental.getCustomerId();
            RentalDto rentalDto = new RentalDto();
            BeanUtils.copyProperties(rental, rentalDto);
            rentalDto.setCar(carService.getById(carId));
            rentalDto.setCustomer(customersService.getById(customerId));
            RentalVo rentalVo = new RentalVo();
            BeanUtils.copyProperties(rental, rentalVo);
            rentalVo.setCustomerName(rentalDto.getCustomer().getName());
            rentalVo.setCarInfo(rentalDto.getCar().getBrand()+rentalDto.getCar().getModel()+" "+rentalDto.getCar().getPlateNumber());

            // 身份证号
            rentalVo.setCartNumber(rentalDto.getCustomer().getCartNumber());
            // 手机号
            rentalVo.setPhone(rentalDto.getCustomer().getPhone());

            rentalVos.add(rentalVo);
        }
        Page<RentalVo> pageInfoVo = new Page<>(page, size);
        pageInfoVo.setRecords(rentalVos);
        pageInfoVo.setTotal(list.getTotal());
        return Result.success(pageInfoVo);
    }


    @Override
    @Transactional
    public Result<String> updateRental(RentalVo rentalVo){
        // 0->-1
        if (rentalVo.getStatus()==-1){
            // car的状态要从租出2变回可用1
            // 得到carId
            Rental rental = this.lambdaQuery()
                    .eq(Rental::getId, rentalVo.getId())
                    .select(Rental::getCarId)
                    .one();
            Integer carId = rental.getCarId();
            carService.updateStatus(carId, 1, 0.0, null);
        }
        // 0->1
        if (rentalVo.getStatus()==1){
            Rental rental = this.lambdaQuery()
                    .eq(Rental::getId, rentalVo.getId())
                    .select(Rental::getCustomerId)
                    .one();
            Integer customerId = rental.getCustomerId();
            log.info("客户租赁次数+1!!!!!!!");
            customersService.lambdaUpdate()
                    .eq(Customers::getId, customerId)
                    .eq(Customers::getDeleted, 0)
                    .setSql("rental_times = rental_times + "+1)
                    .update();
        }
        Rental rental = new Rental();
        BeanUtils.copyProperties(rentalVo, rental);
        return this.updateById(rental) ? Result.success("更新成功") : Result.fail("更新失败");
    }

    @Override
    @Transactional
    public Result<String> deleteRental(Integer id){
        return this.removeById(id) ? Result.success("删除成功") : Result.fail("删除失败");
    }

    @Override
    @Transactional
    public Result<String> updateRentalStatus(Integer id, Integer status){
        // 0->-1
        if (status==-1){
            // car的状态要从租出2变回可用1
            // 得到carId
            Rental rental = this.lambdaQuery()
                    .eq(Rental::getId, id)
                    .select(Rental::getCarId)
                    .one();
            Integer carId = rental.getCarId();
            carService.updateStatus(carId, 1, 0.0, null);
        }
        // 0->1
        if (status==1){
            Rental rental = this.lambdaQuery()
                    .eq(Rental::getId, id)
                    .select(Rental::getCustomerId)
                    .one();
            Integer customerId = rental.getCustomerId();
            log.info("客户租赁次数+1!!!!!!!");
            customersService.lambdaUpdate()
                    .eq(Customers::getId, customerId)
                    .eq(Customers::getDeleted, 0)
                    .setSql("rental_times = rental_times + "+1)
                    .update();
        }
        boolean update = this.lambdaUpdate()
                .eq(Rental::getId, id)
                .set(Rental::getStatus, status)
                .update();
        return update ? Result.success("更新成功") : Result.fail("更新失败");

    }

    @Override
    @Transactional
    public Result<String> addRental(RentalVo rentalVo){
        Rental rental = new Rental();
        BeanUtils.copyProperties(rentalVo, rental);
        rental.setStatus(0);
        // 处理逻辑，要得到客户id和车辆id
        String customerName = rentalVo.getCustomerName();
        String carInfo = rentalVo.getCarInfo();
        String[] split = carInfo.split(" ");
        String brand = split[0];
        String model = split[1];
        String plateNumber = split[2];

        // 客户id
        Customers customer = customersService.lambdaQuery()
                .eq(Customers::getName, customerName)
                .select(Customers::getId)
                .one();
        rental.setCustomerId(customer.getId());

        // 车辆id
        Car car = carService.lambdaQuery()
                .eq(Car::getBrand, brand)
                .eq(Car::getModel, model)
                .eq(Car::getPlateNumber, plateNumber)
                .select(Car::getId)
                .one();
        rental.setCarId(car.getId());
        rental.setDeleted(0);
        log.info("添加租借信息:{}", rental);
        // 车辆状态更新
        carService.updateStatus(car.getId(), 2, (double) 0,null);

        // 这里分两种，如果status==0，则不增加次数；如果是status==1，则增加
//        // 客户租赁次数+1
//        if (rentalVo.getStatus()==1){
//            log.info("客户租赁次数+1!!!!!!!");
//            customersService.lambdaUpdate()
//                    .eq(Customers::getId, rental.getCustomerId())
//                    .eq(Customers::getDeleted, 0)
//                    .setSql("rental_times = rental_times + "+1)
//                    .update();
//        }

        return this.save(rental) ? Result.success("添加成功") : Result.fail("添加失败");
    }

    @Override
    @Transactional
    public Integer getRentalIdByCarId(Integer carId){
        return this.lambdaQuery()
                .eq(Rental::getCarId, carId)
                .eq(Rental::getStatus, 1)
                .eq(Rental::getDeleted, 0)
                .select(Rental::getId)
                .one()
                .getId();
    }

    @Override
    public List<RentalVo> getRentalByCustomerId(Integer customerId){
        List<Rental> rental = this.lambdaQuery()
                .eq(Rental::getCustomerId, customerId)
                .eq(Rental::getDeleted, 0)
                .list();
        List<RentalVo> rentalVos = new ArrayList<>(rental.size());
        for (Rental rental1 : rental) {
            RentalVo rentalVo = new RentalVo();
            BeanUtils.copyProperties(rental1, rentalVo);
            // 这里只要车辆信息够了
            Car car = carService.getById(rental1.getCarId());
            rentalVo.setCarInfo(car.getBrand()+" "+car.getModel()+" "+car.getPlateNumber());
            rentalVos.add(rentalVo);
        }
        return rentalVos;
    }
}
